package top.fengyulou.config.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import top.fengyulou.common.Jr;
import top.fengyulou.common.UserUtils;
import top.fengyulou.common.WebUtils;
import top.fengyulou.config.SysConfig;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private SysConfig sysConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取用户数据
        JSONObject user = UserUtils.getUser(request);
        if (ObjectUtils.isEmpty(user)) {
            if (WebUtils.isAjax(request)) {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print(JSONObject.toJSON(Jr.no("未登录")));
            } else {
                response.sendRedirect(sysConfig.getDomainName() + "/");
            }
            return false;
        }
        return true;
    }
}
